//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using CommunityServer.Components;

namespace CommunityServer.Data
{
    /// <summary>
    /// Summary description for UserManager.
    /// </summary>
    public class UserProviderManager
    {
        private User _currentUser = null;
        private CreateUserStatus _status = CreateUserStatus.UnknownFailure;

        public UserProviderManager(User user)
        {
            _currentUser = user;	
        }

        public User CurrentUser
        {
            get{return _currentUser;}
        }

        public CreateUserStatus Status
        {
            get{return _status;}
        }

        public void Create()
        {
            //will throw an exception if either fail
            this.ValidateNewUserExists();
            IMembershipUser mu = this.CreateMembershipUser();

            

            //Lets update our user's details
            CurrentUser.RefreshMembershipUser(mu);
            IProfileBase pb = MemberRoleProfileProvider.Instance().Profiles.Create(CurrentUser.Username,true);
            CurrentUser.RefreshUserProfile(new Profile(pb));
        }

        public void Update()
        {

            try 
            {
                MemberRoleProfileProvider.Instance().Members.Update(CurrentUser.Member);
            }
            catch (Exception ex) 
            {
                // Check to see if the MemberRole component threw a duplicate email exception.
                //  If so replace the incorrect message it threw with a more useful CS exception
                // NOTE: There is a bug in MemberRole whereas the duplicate email exception message is "The password-answer supplied is invalid"
                //       This due to a typo in the Microsoft.ScalableHosting.Security.SqlMembershipProvider.GetExceptionText method, which 
                //       returns a the wrong message for a status of 7.
                if (ex.Source.ToLower() == "memberrole" && ex.Message.ToLower() == "the password-answer supplied is invalid.")
                    throw new CSException(CreateUserStatus.DuplicateEmailAddress, "Duplicate Email Address", ex);

                throw;
            }


            _status = CreateUserStatus.Updated;
        }

        public void Delete()
        {
            MemberRoleProfileProvider.Instance().Members.Delete(CurrentUser.Username);
            _status = CreateUserStatus.Deleted;
        }

        #region ValidateNewUserExists
        /// <summary>
        /// Validates the User does not alrady exist
        /// </summary>
        protected virtual void ValidateNewUserExists()
        {
            if(MemberRoleProfileProvider.Instance().Members.GetUser(CurrentUser.Username) != null)
            {
                throw new CSException(CreateUserStatus.DuplicateUsername);
            }
        }
        #endregion

        #region CreateMembershipUser
        /// <summary>
        /// Creates a new Membership user based on the this.CurrentUser value
        /// </summary>
        /// <returns></returns>
        protected virtual IMembershipUser CreateMembershipUser()
        {
            string username = CurrentUser.Username;
            string password = CurrentUser.Password;
            string email = CurrentUser.Email;
            string question = CurrentUser.PasswordQuestion;
			string answer = CurrentUser.PasswordAnswer;
            return MemberRoleProfileProvider.Instance().Members.Create(username,password,email,question,answer);
        }

        #endregion

    }
}
